
package com.compuvest.amazon;

import javax.servlet.ServletConfig;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amazonaws.mws.*;
import com.amazonaws.mws.model.*;

public class AmazonService extends HttpServlet {

    def mysql
    def accessKeyId = "AKIAJMAQRZP36JZAUDVA";
    def secretAccessKey = "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";
    def appName = "COMPUVEST";
    def appVersion = "2010-08-31";
    def merchantId = "AVJVFPJRIWFG5";
    def markerplaceId = "AZ4B0ZS3LGLX";

    def void init(ServletConfig config) {
	super.init(config)

        mysql = new AmazonSQLService()
    }

    def void processRequest(request, response) {

        //response.setContentType("text/xml;charset=UTF-8")
        response.setContentType("text/html;charset=UTF-8")

        def exec = request.getParameter("exec"), result = new StringBuilder()
        if(exec) {
            result << "exec=${exec}<br/>"
            if(exec == 'getrequest1') {
                result << getReportRequst1()
            }
            else if(exec == 'getrequest2') {
                result << getReportRequst2()
            }
            else if(exec == 'getrequest3') {
                result << getReportRequst3()
            }
        }

        def out = response.getWriter()
        try {
            out.print(result)
        }
        finally {
            out.close()
        }
    }


    def getReportRequst1() {

        def result = new StringBuilder()
        result << "getReportRequst<br/>"

        def config = new MarketplaceWebServiceConfig()
        config.setServiceURL("https://mws.amazonservices.com")

        def service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);

        def IdList marketplaces = new IdList(Arrays.asList(markerplaceId));

        def request = new RequestReportRequest()
		        .withMerchant(merchantId)
		        .withMarketplaceIdList(marketplaces)
		        //.withReportType("_GET_ORDERS_DATA_")
		        .withReportType("_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_")

        def requestResponse = service.requestReport(request);
        def responsexml = requestResponse.toXML()
        //println "responsexml=${responsexml}"

        def parser = new XmlSlurper()
        def root1
        try {
            root1 = parser.parseText(responsexml)
        }
        catch(e) {
            println ">>>AmazonService:requestResponse bad XML file=${responsexml}"
            return "requestResponse bad XML<br/>"
        }
        //println "root=${root1}"

        def rootname1 = root1.name()
        //println "root.name1=${rootname1}"
        def reportRequestId = root1.RequestReportResult.ReportRequestInfo.ReportRequestId.text()
        def reportProcessingStatus = root1.RequestReportResult.ReportRequestInfo.ReportProcessingStatus.text()
        //println "\nReportRequestId=${reportRequestId}\nReportProcessingStatus=${reportProcessingStatus}"
        result << "ReportRequestId=${reportRequestId}</br>"
        result << "ReportProcessingStatus=${reportProcessingStatus}</br>"

        def listRequest = new GetReportListRequest()
        listRequest.withMerchant(merchantId)


        def listResponse = service.getReportList(listRequest)

        //result << "<br/>listResponse.isSetGetReportListResult()=(${listResponse.isSetGetReportListResult()})</br>"
        if(listResponse.isSetGetReportListResult()) {
            def listxml = listResponse.toXML()
            //println "listxml=${listxml}"

            def root2
            try {
                root2 = parser.parseText(listxml)
            }
            catch(e) {
                println ">>>AmazonService:listResponse bad XML file=${listxml}"
                return "listResponse bad XML<br/>"
            }

            def rootname2 = root2.name()
            //println "root.name2=${rootname2}"
            result << "<br/>Reportlist</br>"
            root2.GetReportListResult.ReportInfoList.each { report->

                result << "--------<br/>ReportId=${report.ReportId}</br>ReportRequestId=${report.ReportRequestId}</br>Acknowledged=${report.Acknowledged}</br>"
                //println "\nReportId=${report.ReportId}\nReportRequestId=${report.ReportRequestId}\nAcknowledged=${report.Acknowledged}"
            }
        }

        return result.toString()
    }

    def getReportRequst2() {

        def result = new StringBuilder()
        result << "getReportRequst<br/>"

        def config = new MarketplaceWebServiceConfig()
        config.setServiceURL("https://mws.amazonservices.com")

        def service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);

        def IdList marketplaces = new IdList(Arrays.asList(markerplaceId));

        def request = new RequestReportRequest()
		        .withMerchant(merchantId)
		        .withMarketplaceIdList(marketplaces)
		        //.withReportType("_GET_ORDERS_DATA_")
		        .withReportType("_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_")

        def requestResponse = service.requestReport(request);
        def responsexml = requestResponse.toXML()
        //println "responsexml=${responsexml}"

        def parser = new XmlSlurper()
        def root1
        try {
            root1 = parser.parseText(responsexml)
        }
        catch(e) {
            println ">>>AmazonService:requestResponse bad XML file=${responsexml}"
            return "requestResponse bad XML<br/>"
        }
        //println "root=${root1}"

        def rootname1 = root1.name()
        //println "root.name1=${rootname1}"
        def reportRequestId = root1.RequestReportResult.ReportRequestInfo.ReportRequestId.text()
        def reportProcessingStatus = root1.RequestReportResult.ReportRequestInfo.ReportProcessingStatus.text()
        //println "\nReportRequestId=${reportRequestId}\nReportProcessingStatus=${reportProcessingStatus}"
        result << "ReportRequestId=${reportRequestId}</br>"
        result << "ReportProcessingStatus=${reportProcessingStatus}</br>"

        def listRequest = new GetReportListRequest()
        listRequest.withMerchant(merchantId)
        listRequest.setReportRequestIdList(new IdList(Arrays.asList(reportRequestId)))


        def listResponse = service.getReportList(listRequest)
        def listxml = listResponse.toXML()
        //println "listxml=${listxml}"


        def root2
        try {
            root2 = parser.parseText(listxml)
        }
        catch(e) {
            println ">>>AmazonService:listResponse bad XML file=${listxml}"
            return "listResponse bad XML<br/>"
        }

        def rootname2 = root2.name()
        //println "root.name2=${rootname2}"
        result << "<br/>Reportlist set setReportRequestIdList(${reportRequestId})</br>"
        root2.GetReportListResult.ReportInfoList.each { report->

            result << "--------<br/>ReportId=${report.ReportId}</br>ReportRequestId=${report.ReportRequestId}</br>Acknowledged=${report.Acknowledged}</br>"
            //println "\nReportId=${report.ReportId}\nReportRequestId=${report.ReportRequestId}\nAcknowledged=${report.Acknowledged}"
        }

        return result.toString()
    }

    def getReportRequst3() {

        def result = new StringBuilder()
        result << "getReportRequst<br/>"

        def config = new MarketplaceWebServiceConfig()
        config.setServiceURL("https://mws.amazonservices.com")

        def service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);

        def IdList marketplaces = new IdList(Arrays.asList(markerplaceId));

        def request = new RequestReportRequest()
		        .withMerchant(merchantId)
		        .withMarketplaceIdList(marketplaces)
		        //.withReportType("_GET_ORDERS_DATA_")
		        .withReportType("_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_")

        def requestResponse = service.requestReport(request);
        def responsexml = requestResponse.toXML()
        //println "responsexml=${responsexml}"

        def parser = new XmlSlurper()
        def root1
        try {
            root1 = parser.parseText(responsexml)
        }
        catch(e) {
            println ">>>AmazonService:requestResponse bad XML file=${responsexml}"
            return "requestResponse bad XML<br/>"
        }
        //println "root=${root1}"

        def rootname1 = root1.name()
        //println "root.name1=${rootname1}"
        def reportRequestId = root1.RequestReportResult.ReportRequestInfo.ReportRequestId.text()
        def reportProcessingStatus = root1.RequestReportResult.ReportRequestInfo.ReportProcessingStatus.text()
        //println "\nReportRequestId=${reportRequestId}\nReportProcessingStatus=${reportProcessingStatus}"
        result << "ReportRequestId=${reportRequestId}</br>"
        result << "ReportProcessingStatus=${reportProcessingStatus}</br>"

        def listRequest = new GetReportListRequest()
        listRequest.withMerchant(merchantId)


        def listResponse = service.getReportList(listRequest)

        //result << "<br/>listResponse.isSetGetReportListResult()=(${listResponse.isSetGetReportListResult()})</br>"
        if(listResponse.isSetGetReportListResult()) {
            GetReportListResult  getReportListResult = listResponse.getGetReportListResult();
            if(getReportListResult.isSetNextToken()) {
                getReportListResult.getNextToken();

                def reportInfoListList = getReportListResult.getReportInfoList();
                println "reportInfoListList=${reportInfoListList}"
                for(ReportInfo reportInfoList : reportInfoListList) {
                //    if(reportInfoList.getRequestStatus().equals("_DONE_")) {
                //        result << "reportInfoList.getReportId()=${reportInfoList.getReportId()}</br>"
                        //orderReports.add(reportInfoList.getReportId());
                //    }
                }
            }
        }

        return result.toString()
    }

    def void doGet(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    def void doPost(HttpServletRequest request, HttpServletResponse response) {
        processRequest(request, response)
    }
    String getServletInfo() {
        return "AmazonService"
    }
    def void destroy() {
        mysql = null
    }

}
